import React from 'react';
import ReactDOM from 'react-dom';

class Modal extends React.Component {
    constructor(props) {
        super(props);
        //this.el = document.createElement('div');
    }

    componentDidMount() {
       //modalRoot?.appendChild(this.el);
    }

    componentWillUnmount() {
        //modalRoot?.removeChild(this.el);
    }

    render() {
        const modalRoot = document.getElementById('modal-root');
        return ReactDOM.createPortal(
            this.props.children,
            //this.el
            modalRoot
        );
    }
}

// const Modal = (props) => {
//     const modalRoot = document.getElementById('modal-root');
//     return ReactDOM.createPortal(
//         props.children,
//         //this.el
//         modalRoot
//     );
// }



class Parent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            clicks: 0,
            isOpen: false,
        }
        this.handleClick = this.handleClick.bind(this);
        this.toggleClick = this.toggleClick.bind(this);
    }

    handleClick() {
        // 当子元素里的按钮被点击时，
        // 这个将会被触发更新父元素的 state，
        // 即使这个按钮在 DOM 中不是直接关联的后代
        this.setState(state => ({
          clicks: state.clicks + 1
        }));
    }

    toggleClick() {
        this.setState(state => ({
            isOpen: !state.isOpen
        }));
    }

    render() {
        return (
            <div style={{ cursor: 'pointer'}} onClick={this.handleClick}>
                <p>Number of clicks: {this.state.clicks}</p>
                <p>
                    Open up the browser DevTools
                    to observe that the button
                    is not a child of the div
                    with the onClick handler.
                </p>
                <button onClick={ this.toggleClick }>展示Modal</button>
                
                {
                    this.state.isOpen ? 
                    <Modal>
                        <Child />
                    </Modal>:''
                }
            </div>
        );
    }
}

function Child() {
    // 这个按钮的点击事件会冒泡到父元素
    // 因为这里没有定义 'onClick' 属性
    return (
      <div className="modal">
        <button>点击</button>
      </div>
    );
}

export default function Portals() {
    return (
        <div>
            <div id="app-root">
                <Parent />
            </div>
            <div id="modal-root"></div>
        </div>
    )
}